package com.dwxt.cdms.applets.service;

import com.dwxt.cdms.base.Page;
import com.dwxt.cdms.dao.ConversationMapper;
import com.dwxt.cdms.dao.CustomerMapper;
import com.dwxt.cdms.dao.HealthWarnRecordMapper;
import com.dwxt.cdms.dao.RelationMapper;
import com.dwxt.cdms.entity.*;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.base.YesOrNo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ConversationService {

    @Autowired
    private ConversationMapper conversationMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private HealthWarnRecordMapper healthWarnRecordMapper;
    @Autowired
    private RelationMapper relationMapper;

    public BaseResult addRelation(Integer customerId, Integer relateId, String relate) {

        Relation relation = new Relation();
        relation.setCustomerId(customerId);
        relation.setRelateId(relateId);
        if (relate!=null){
            relation.setRelation(relate);
        }
        relation.setCreateTime(new Date());
        if (relation.getCustomerId().equals(relation.getRelateId())) {
            return BaseResult.build(StatusCode.CAN_NOT_BINDYOURSELF);
        }
        RelationExample example = new RelationExample();
        example.createCriteria().andCustomerIdEqualTo(customerId).andRelateIdEqualTo(relateId);
        List<Relation> relations = relationMapper.selectByExample(example);
        if (relations.size() > 0) {
            return BaseResult.build(StatusCode.ALREADY_RELATION);
        }

        relationMapper.insertSelective(relation);

        /*ConversationExample conversationExample = new ConversationExample();
        conversationExample.createCriteria().andCustomerIdEqualTo(customerId).andRelateIdEqualTo(relateId).andStatusEqualTo(2);
        long count = conversationMapper.countByExample(conversationExample);
        if (count > 0) {
            return BaseResult.build(StatusCode.ALREADY_SEND);
        }*/

        /*Customer customer = customerMapper.selectByPrimaryKey(customerId);

        Conversation conversation = new Conversation();
        conversation.setCustomerId(customerId);
        conversation.setRelateId(relateId);
        conversation.setTitle("关联人添加");
        StringBuilder sb = new StringBuilder();
        sb.append("用户:" + customer.getName() + ",电话:" + customer.getPhone() + ",申请添加你为联系人。同意后可以查看健康数据。");
        conversation.setContent(sb.toString());
        conversation.setStatus(2);
        conversation.setIsNew(YesOrNo.YES);
        conversationMapper.insertSelective(conversation);*/
        return BaseResult.ok();
    }

    public BaseResult selectConversionPage(Page page, Integer customerId, Integer type) {
        if (type == 2) {
            ConversationExample example = new ConversationExample();
            example.setOrderByClause("creat_time desc");
            example.createCriteria().andRelateIdEqualTo(customerId);
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            List<Conversation> conversations = conversationMapper.selectByExample(example);
            PageInfo pageInfo = new PageInfo(conversations);
            conversationMapper.updateStatus(customerId);
            return BaseResult.ok(pageInfo);
        }
        if (type == 1) {
            List<Conversation> conversations = new ArrayList<>();
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            List<HealthMessage> healthMessages = conversationMapper.getHealthMessageByUserId(customerId);
            if (healthMessages.size() > 0) {
                for (HealthMessage healthMessage : healthMessages) {
                    Conversation conversation = new Conversation();
                    conversation.setContent(healthMessage.getContent());
                    conversation.setCreatTime(healthMessage.getCrateTime());
                    conversation.setId(0);
                    conversation.setStatus(0);
                    conversation.setTitle(healthMessage.getType());
                    conversations.add(conversation);
                }
            }
            PageInfo pageInfo = new PageInfo(healthMessages);
            pageInfo.setList(conversations);
            conversationMapper.updateStatus(customerId);
            return BaseResult.ok(pageInfo);
        } else {
            return BaseResult.build(StatusCode.TYPE_ERROR);
        }
       /* List<HealthMessage> healthMessages = conversationMapper.getHealthMessageByUserId(customerId);
        if (healthMessages.size()>0){
            for (HealthMessage healthMessage : healthMessages) {
                Conversation conversation = new Conversation();
                conversation.setContent(healthMessage.getContent());
                conversation.setCreatTime(healthMessage.getCrateTime());
                conversation.setId(0);
                conversation.setStatus(0);
                conversation.setTitle(healthMessage.getType());
                conversations.add(conversation);
            }
        }

        PageInfo pageInfo = new PageInfo(conversations);
        conversationMapper.updateStatus(customerId);
        return BaseResult.ok(pageInfo);*/
    }

    @Transactional
    public BaseResult agreeOrRefund(Integer id, Integer status) {
        Conversation conversation = conversationMapper.selectByPrimaryKey(id);
        if (conversation.getStatus() != 2) {
            return BaseResult.build(StatusCode.NOT_ALLOW);
        }
        //是否已经同意或拒绝，只能解绑
        /*ConversationExample example = new ConversationExample();
        example.createCriteria().andCustomerIdEqualTo(conversation.getCustomerId()).andRelateIdEqualTo(conversation.getRelateId()).andStatusNotEqualTo(2);
        List<Conversation> conversations = conversationMapper.selectByExample(example);
        if (conversations.size() > 0) {
            return BaseResult.build(StatusCode.NOT_ALLOW);
        }*/

        RelationExample relationExample = new RelationExample();
        relationExample.createCriteria().andCustomerIdEqualTo(conversation.getCustomerId()).andRelateIdEqualTo(conversation.getRelateId());
        List<Relation> relations = relationMapper.selectByExample(relationExample);
        if (relations.size() > 0) {
            return BaseResult.build(StatusCode.NOT_ALLOW);
        }

        conversation.setStatus(status);
        conversationMapper.updateByPrimaryKeySelective(conversation);

        Customer customer = customerMapper.selectByPrimaryKey(conversation.getRelateId());

        Conversation conver = new Conversation();
        conver.setCustomerId(conversation.getRelateId());
        conver.setRelateId(conversation.getCustomerId());
        conver.setTitle("关联人添加");
        conver.setStatus(status);
        StringBuilder sb = new StringBuilder();
        if (status == YesOrNo.YES) {
            sb.append("用户:" + customer.getName() + ",电话:" + customer.getPhone() + ",已经通过你的添加为关联人的申请,可在关联人列表查看。");
        } else {
            sb.append("用户:" + customer.getName() + ",电话:" + customer.getPhone() + ",已经拒绝你的添加为关联人的申请。");
        }
        conver.setContent(sb.toString());
        conver.setIsNew(YesOrNo.YES);
        conversationMapper.insertSelective(conver);

        if (status == YesOrNo.YES) {
            Relation relation = new Relation();
            relation.setRelateId(conversation.getRelateId());
            relation.setCustomerId(conversation.getCustomerId());
            relationMapper.insertSelective(relation);
        }

        return BaseResult.ok();
    }

    public BaseResult updateConversationToOld(Integer customerId) {
        Conversation conversation = new Conversation();
        conversation.setIsNew(YesOrNo.NO);

        ConversationExample example = new ConversationExample();
        example.createCriteria().andIsNewEqualTo(YesOrNo.YES).andRelateIdEqualTo(customerId);
        conversationMapper.updateByExampleSelective(conversation, example);
        return BaseResult.ok();
    }

    public BaseResult isNewConversation(Integer customerId) {
        ConversationExample example = new ConversationExample();
        example.createCriteria().andIsNewEqualTo(YesOrNo.YES).andRelateIdEqualTo(customerId);
        Long count = conversationMapper.countByExample(example);
        Long count1 = healthWarnRecordMapper.getCountByCustomerIdcustomerId(customerId);
        if (count1 != null) {
            count = count + count1;
        }
        return BaseResult.ok(count != null && count > 0 ? count : 0);
    }
}
